
// 445.两数相加II
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    ListNode* reverseList(ListNode* head)
    {
        ListNode* phead = new ListNode;
        phead->next = nullptr;
        ListNode* cur = head;
        while(cur)
        {
            ListNode *next = cur->next;
            cur->next = phead->next;
            phead->next = cur;
            cur = next;
        }
        ListNode *ret = phead->next;
        delete phead;
        return ret;
    }

public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *cur1 = reverseList(l1) , *cur2 = reverseList(l2);

        ListNode* phead = new ListNode;
        phead->next = nullptr;
        int flag = 0;
        while(cur1 || cur2 || flag)
        {
            int sum = flag;
            if(cur1) 
            {
                sum += cur1->val;
                cur1 = cur1->next;
            }
            if(cur2)
            {
                sum += cur2->val;
                cur2 = cur2->next;
            }
            ListNode* newnode = new ListNode(sum%10);
            flag = sum/10;
            newnode->next = phead->next;
            phead->next = newnode;
        }
        ListNode* ans = phead->next;
        delete phead;
        return ans;
    }
};